﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace Skyhook.Core.Xml
{
    class XmlDocumentsCache : IEnumerable<XmlDocumentWithFileName>
    {
        Dictionary<string, XmlDocumentWithFileName> Documents = null;

        public string Path { get; private set; }
        public bool IsLoaded { get; private set; }
        
        public XmlDocumentsCache()
        {
            Documents = new Dictionary<string, XmlDocumentWithFileName>();

            Path = null;
            IsLoaded = false;
        }

        public void LoadFromPath(string path)
        {
            Documents.Clear();

            Path = GetPathFromString(path);

            string[] filenames = Directory.EnumerateFiles(Path, "*.xml", SearchOption.AllDirectories).ToArray();

            foreach (string filename in filenames)
            {
                Documents.Add(filename, new XmlDocumentWithFileName(filename));
            }

            IsLoaded = true;
        }

        string GetPathFromString(string path)
        {
            path = path.TrimEnd('\\');
            path += "\\";

            return path;
        }

        public XmlDocumentWithFileName this[string filename]
        {
            get
            {
                return Documents[filename];
            }
        }

        IEnumerator<XmlDocumentWithFileName> IEnumerable<XmlDocumentWithFileName>.GetEnumerator()
        {
            return new XmlDocumentsCacheEnumerator(Documents);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new XmlDocumentsCacheEnumerator(Documents);
        }
    }
}
